package com.guozi.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UpLoadController {
	
	@RequestMapping("/up") 
	public String up(){
		return "upload";
	}
	
	@RequestMapping("/upload")  
    public String upload(@RequestParam MultipartFile[] myfiles,HttpServletRequest request) throws IOException {  
		if(request.getCharacterEncoding() == null){
			request.setCharacterEncoding("UTF-8");
		}
        for(MultipartFile file : myfiles){     
            //此处MultipartFile[]表明是多文件,如果是单文件MultipartFile就行了  
            if(file.isEmpty()){   
                System.out.println("文件未上传!");  
            }  
          else{  
        	  	Calendar ca=Calendar.getInstance();
                //得到上传的文件名  
                String fileName ="("+ ca.get(Calendar.YEAR)+(ca.get(Calendar.MONTH)+1)+ca.get(Calendar.DATE)+ca.get(Calendar.HOUR_OF_DAY)+ca.get(Calendar.MINUTE)+ca.get(Calendar.SECOND)+")"+file.getOriginalFilename();
                String rootPath= request.getSession().getServletContext().getRealPath("/WEB-INF/images/"+fileName); 
                System.out.println("文件名:"+fileName);
                System.out.println("路径:"+rootPath);
//                //把文件上传至path的路径  
               File localFile = new File(rootPath);  
               file.transferTo(localFile);  
                }  
            return "uploadSuccess";  
            }  
       return "error";
    }  
	
	public static String urlEncodeUTF8(String source){
		String result=source;
		try {
			result=java.net.URLEncoder.encode(source, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	public static void main(String[] args){
		Calendar ca=Calendar.getInstance();
		System.out.println("("+ca.get(Calendar.YEAR)+(ca.get(Calendar.MONTH)+1)+ca.get(Calendar.DATE)+ca.get(Calendar.HOUR_OF_DAY)+ca.get(Calendar.MINUTE)+ca.get(Calendar.SECOND)+")");
		System.out.println(ca.get(Calendar.MONTH)+1);
	}
	
}
